<template>
  <a-spin :spinning="isLoading">
    <page-layout>
      <a-form ref="formRef" :model="formState.data" :rules="formRules">
        <div class="pre-title">{{ "订单详情" }}</div>
        <a-card>
          <a-row :gutter="[10, 10]">
            <a-col :span="8">
              <a-form-item :label="'订单编号'">{{
                formState.data.orderNo
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'学生姓名'">{{
                formState.data.stuName
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'订单金额'">{{
                formState.data.totalAmt
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'优惠金额'">{{
                formState.data.discountAmt
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'特殊优惠金额'">{{
                formState.data.specialAmt
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'已收总金额'">{{
                formState.data.receivedTotalAmt
              }}</a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'剩余应收总金额'">{{
                state.unpaid
              }}</a-form-item>
            </a-col>
            <!-- <a-col :span="8">
              <a-form-item :label="'本次应收金额'">{{
                formState.data.recAmt
              }}</a-form-item>
            </a-col> -->
          </a-row>
        </a-card>
        <div class="pre-title">{{ "收款信息" }}</div>
        <a-card>
          <a-row :gutter="[10, 10]">
            <a-col :span="8">
              <a-form-item :label="'支付方式'">
                <a-select v-model:value="formState.data.payType">
                  <a-select-option
                    v-for="(item, index) in dictLists.data[dictEnum.PAY_TYPE]"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'收款金额'" name="money">
                <a-input-number
                  style="width: 100%"
                  v-model:value="formState.data.money"
                  :min="0"
                  :max="1000000000"
                  :step="1"
                  :precision="2"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="'收款备注'">
                <a-textarea
                  v-model:value="formState.data.remark"
                  placeholder="请输入"
                  :rows="{ min: 2, max: 4 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
      <footer-button class="mt-20" :reserse="true" :buttons="state.buttons" />
    </page-layout>
  </a-spin>
</template>
<script>
import { selectById, pay } from "@/api/module/student/order-manage";
import { reactive, ref, computed, createVNode, onActivated } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message, modal, Form } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useI18n } from "vue-i18n";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
const useForm = Form.useForm;
export default {
  name: "order-manage-collection",
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    let isLoading = ref(false);
    let formRef = ref();
    let state = reactive({
      buttons: [
        {
          name: "collection",
          event: () => handleCollection(),
          type: "primary",
          code: "",
        },
      ],
      unpaid: 0
    });
    state.unpaid = computed(() => {
      let price = 0
      let {totalAmt, discountAmt, specialAmt, receivedTotalAmt } = formState.data
      totalAmt ?? (totalAmt = 0)
      discountAmt ?? (discountAmt = 0)
      specialAmt ?? (specialAmt = 0)
      receivedTotalAmt ?? (receivedTotalAmt = 0)
      price = parseFloat(totalAmt) - parseFloat(discountAmt) - parseFloat(specialAmt) - parseFloat(receivedTotalAmt)
      return price.toFixed(2)
    })
    let formState = reactive({
      data: {},
    });

    let dictLists = reactive({
      data: {},
    });
    const formRules = reactive({
      money: [
        { type: 'number', required: true, message: "请输入收款金额", trigger: 'blur' },
        { type: 'number', validator: (rules, value, callback) => {
            if (value && parseFloat(value) > state.unpaid) {
              formState.data.money = 0
              return Promise.reject('收款金额应小于剩余应收总额')
            }
            return Promise.resolve();
          }, trigger: 'change' },
      ],
    })
    const { resetFields, validate, validateInfos } = useForm(
      formState.data,
      formRules
    );
    const handleCollection = () => {
      formRef.value.validate().then(() => {
        modal.confirm({
          title: "请先核对收款信息，确认收款吗?",
          icon: createVNode(ExclamationCircleOutlined),
          okText: "确定",
          cancelText: "取消",
          onOk() {
            isLoading.value = true
            const { money, payType, remark, orderNo, id } = formState.data
            let params = {
              money,
              payType,
              remark,
              orderId: id,
              orderNo: orderNo,
            }
            // console.log();
            pay(params).then(res => {
              if (res.code === 200) {
                message.success('收款成功')
                router.push('/studentrtv/order-manage')
              } else {
                message.error('收款失败')
              }
              console.log('res: ', res);
            }).finally(() => {
              isLoading.value = false
            })
          },
        });
      })
    };

    onActivated(async () => {
      dictLists.data = await getDictByCodesReturnObj([dictEnum.PAY_TYPE]);
      const { id } = route.query;
      if (id) {
        // formState.data = { ... route.query }
        const data = await selectById({ id });
        if (data.code == 200 && data.data) {
          formState.data = { ...data.data, stuName: data.data.stuBusp ? data.data.stuBusp.stuName : '' }
        } else {
          formState.data = {}
        }
      }
    });

    
    return {
      t,
      state,
      isLoading,
      formState,
      formRef,
      dictLists,
      dictEnum,
      formRules,
      resetFields,
      validateInfos,
    };
  },
};
</script>
<style scoped>
.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}
</style>